#!/bin/bash

function help() {
    echo "Usage:"
    echo "    ./install_ceph_from_git.sh [branch]"
    echo "        branch: The branch which will be installed"
    echo "        Default branch is master"
}

if [[ $# -eq 1 && ( $1 == "-h" || $1 == "--help" ) ]]; then
    help
    exit
elif [ $# -gt 1 ]; then
    echo "Too many args"
    help
    exit
fi

pip_config_path="$HOME/.pip"
install_path="$HOME"
if [[ $# -eq 2 && ( $1 == "-p" || $1 == "--path" ) ]]; then
    shift
    install_path=$1
fi

# clone ceph source code from gitee
git clone https://gitee.com/czy233/ceph-demo.git $install_path/ceph-demo
if [ $? -ne 0 ]; then
    echo "git clone gitee.com/czy233/ceph-demo error"
    exit
fi

# install pip & set pip sources
sudo apt-get -y install python3-pip
if [ $? -ne 0 ]; then
    echo "install pip3 error"
    exit -1
fi
# change pip source
if [ ! -d $pip_config_path ]; then
    mkdir ~/.pip
fi
sudo rm -rf ~/.pip/pip.conf
echo "[global]
index-url = https://mirrors.aliyun.com/pypi/simple/
[install]
trusted-host=mirrors.aliyun.com" >> ~/.pip/pip.conf

# install deps & cmake & build & install
cd $install_path/ceph-demo
if [ $# -eq 0 ]; then
    echo "git checkout master"
    git checkout master
    if [ $? -ne 0 ]; then
        echo "Branch [master] not exist"
        exit -1
    fi
else
    echo "git checkout $1"
    git checkout $1
    if [ $? -ne 0 ]; then
        echo "Branch [$1] not exist"
        exit -1
    fi
fi

# install deps which required by ceph
./install-deps.sh
if [ $? -ne 0 ]; then
    echo "install deps error"
    exit -1
fi
# do cmake to generate Makefiles
ARGS="-DCMAKE_BUILD_TYPE=RelWithDebInfo -DWITH_MANPAGE=OFF -DWITH_BABELTRACE=OFF -DWITH_MGR_DASHBOARD_FRONTEND=OFF" ./do_cmake.sh
if [ $? -ne 0 ]; then
    echo "do_cmake error"
    exit -1
fi
# make & install
cd build
make -j16
if [ $? -ne 0 ]; then
    make -j8
    if [ $? -ne 0 ]; then
        echo "make ceph error"
        exit -1
    fi
fi
sudo make install -j24
if [ $? -ne 0 ]; then
    echo "install ceph error"
    exit -1
fi
# config ceph run environment
sudo ldconfig
export PYTHONPATH=/usr/local/lib/python3/dist-packages/:$PYTHONPATH
export PYTHONPATH=/usr/local/lib/python3.8/dist-packages/:$PYTHONPATH
export PYTHONPATH=/usr/lib/python3/dist-packages/:$PYTHONPATH
sudo cp $install_path/ceph-demo/src/pybind/ceph_argparse.py /usr/lib/python3.8/
sudo cp $install_path/ceph-demo/src/pybind/ceph_daemon.py /usr/lib/python3.8/
sudo cp $install_path/ceph-demo/src/pybind/ceph_volume_client.py /usr/lib/python3.8/
sudo cp $install_path/ceph-demo/build/lib/librados.so.2 /usr/lib
sudo cp $install_path/ceph-demo/build/lib/libcephfs.so.2 /lib/x86_64-linux-gnu
sudo cp $install_path/ceph-demo/build/lib/librbd.so.1 /lib/x86_64-linux-gnu
sudo cp -r $install_path/ceph-demo/src/python-common/ceph /usr/lib/python3/dist-packages/